package javaSocket;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;


@Slf4j
public class GroupChatClientExample {

    private Selector selector;
    private SocketChannel socketChannel;
    private static final int PORT = 6667;
    private static final String HOST ="127.0.0.1";
    private String userName;


    public static void main(String[] args) throws IOException {
        GroupChatClientExample clientExample = new GroupChatClientExample();
        new Thread(){
            @Override
            public void run() {
                while (true){
                    try {
                        clientExample.readInfo();
                        Thread.sleep(3000);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String s = scanner.nextLine();
            clientExample.sendInfo(s);
        }
    }
    public GroupChatClientExample() throws IOException {
        selector = Selector.open();
        socketChannel= socketChannel.open(new InetSocketAddress(HOST,PORT));
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
        userName = socketChannel.getRemoteAddress().toString().substring(1);
        System.out.println(userName +"is ok ....");
    }
    
    private void sendInfo(String info) throws IOException {
        info = userName + "说："+info;
        socketChannel.write(ByteBuffer.wrap(info.getBytes(StandardCharsets.UTF_8)));
    }
    
    private void readInfo() throws IOException {
        int readChannels = selector.select(2000);
        if (readChannels > 0){
            for (Iterator<SelectionKey> it =selector.selectedKeys().iterator();it.hasNext();){
                SelectionKey key = it.next();
                if (key.isReadable()){
                    SocketChannel channel = (SocketChannel) key.channel();
                    channel.configureBlocking(false);
                    ByteBuffer buffer = ByteBuffer.allocate(128);
                    channel.read(buffer);
                    
                    String msg = new String(buffer.array()).trim();
                    System.out.println(msg);
                }else {
                    log.error("没有可以用的通道");
                }
                it.remove();
            }
        }
    }
    
}
